<template>
  <div class="globalHeader">
    <a-row id="globalHeader" align="center" :wrap="false">
      <a-col flex="auto">
        <!-- 菜单 -->
        <a-menu mode="horizontal" :selected-keys="selectedKeys" @menu-item-click="doMenuClick">
          <a-menu-item key="0" :style="{ padding: 0, marginRight: '38px' }" disabled>
            <div class="title-bar">
              <img class="logo" src="@/assets/logo.png" alt="logo" />
              <div class="title">Online Judge</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in flatRoutes" :key="item.path">
            <span>{{ item.name }}</span>
          </a-menu-item>
          <a-sub-menu v-for="item in nestedRoutes" :key="item.path">
            <template #title>
              <span>{{ item.name }}</span>
            </template>
            <a-menu-item v-for="child in item.children" :key="child.path">
              <span>{{ child.name }}</span>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </a-col>
      <a-col flex="200px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown trigger="hover">
              <ASpace>
                <a-avatar :image-url="loginUserStore.loginUser.userAvatar"></a-avatar>
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </ASpace>
              <template #content>
                <a-doption v-if="loginUserStore.loginUser.id" @click="doInfo">
                  <icon-user />
                  个人主页
                </a-doption>
                <a-doption v-if="loginUserStore.loginUser.id" @click="logout" style="color: red">
                  <icon-poweroff />
                  退出登录
                </a-doption>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-avatar :size="40">
              <div class="unlogged-in" @click="goToLogin">未登录</div>
            </a-avatar>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>
<script setup lang="ts">
// 过滤出不隐藏在菜单中的路由项
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import checkAccess from '@/access/checkAccess.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { userLogoutUsingPost } from '@/api/userController.ts'
import { Message } from '@arco-design/web-vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

const visibleRoutes = computed(() => {
  return router.options.routes.filter((item) => {
    // 检查是否在菜单中隐藏
    if (item.meta?.hideInMenu) return false
    if (!checkAccess(loginUserStore.loginUser, item.meta?.access as string)) {
      return false
    }
    return true
  })
})
// 过滤出扁平路由
const flatRoutes = computed(() => {
  return visibleRoutes.value.filter((route) => !route.children)
})
// 过滤出嵌套路由
const nestedRoutes = computed(() => {
  return visibleRoutes.value.filter((route) => route.children)
})
// 当前选中的菜单项
const selectedKeys = ref(['/'])
// 路由跳转的时候更新选中的菜单项
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})
// 点击菜单跳转到对应应用
const doMenuClick = (key: string) => {
  router.push({ path: key })
}
// 退出登录
const logout = async () => {
  try {
    const res = await userLogoutUsingPost()
    if (res.data.code === 0) {
      await loginUserStore.setLoginUser({
        userName: '未登录',
      })
      Message.success('退出登录成功')
      await router.push('/user/login')
    } else {
      Message.error(`退出登录失败，${res.data.message}`)
    }
  } catch (error) {
    Message.error('退出登录时发生错误：' + error.message)
  }
}
// 跳转到登录页面
const goToLogin = () => {
  router.push({
    path: 'user/login',
    replace: true,
  })
}
// 跳转到个人信息页面
const doInfo = () => {
  router.push('user/info')
}
</script>
<style scoped>
.globalHeader .title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}

/* 头像样式 */
.avatar img {
  border-radius: 80%;
}
</style>
